package com.dcms.power.controller;

import com.dcms.power.annotation.ArchivesLog;
import com.dcms.admin.controller.BaseController;
import com.dcms.power.bean.Menu;
import com.dcms.power.bean.RoleMenu;
import com.dcms.power.dao.RoleMenuMapper;
import com.dcms.power.service.IMenuService;
import com.dcms.power.service.IRoleMenuService;
import com.dcms.util.ResultBean;
import com.dcms.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.*;

/**
 * \*
 * \* @name: RoleMenuController
 * \* @author: 武佳伟丶
 * \* @date: 2018/4/10 0010
 * \* @time: 18:30
 * \* @description: To change this template use File | Settings | File Templates.
 * \
 */
@Controller
@RequestMapping("roleMenu")
public class RoleMenuController extends BaseController{

    @Autowired
    private IRoleMenuService roleMenuService;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private IMenuService menuService;

    @RequestMapping("update/node")
    @ResponseBody
    @ArchivesLog(message = "修改角色权限")
    @Transactional(rollbackFor = Exception.class)
    public ResultBean updateNode(String treeNodeStr, Integer roleId){
        Date now = new Date();
        //记录要新增的menuId
        List<Integer> menuIds4Insert = new ArrayList<Integer>();
        //记录要删除的menuId
        List<Integer> menuIds4Delete = new ArrayList<Integer>();

        JSONObject jsonObject = JSONObject.fromObject(treeNodeStr);
        boolean isParent = jsonObject.getBoolean("isParent");
        int menuId = jsonObject.getInt("id");
        boolean checked = jsonObject.getBoolean("checked");

        //选中 -> insert
        if (checked){
            menuIds4Insert.add(menuId);
        }
        //未选中 -> delete
        else {
            menuIds4Delete.add(menuId);
        }

        //判断该节点是否父节点，如果是父节点，应同时修改子节点选中状态
        if (isParent) {
            JSONArray childrenArray = jsonObject.getJSONArray("children");
            for (int i = 0; i < childrenArray.size(); i++) {
                JSONObject childObj = (JSONObject) childrenArray.get(i);
                int childMenuId = childObj.getInt("id");
                if (checked){
                    menuIds4Insert.add(childMenuId);
                } else {
                    menuIds4Delete.add(childMenuId);
                }
            }
        }
        //如果是子节点，需要同时修改父节点选中状态
        else {
            //获取pid
            Menu menu = menuService.selectByPrimaryKey(menuId);
            int pid = menu.getPid();

            //获取兄弟子节点的选中状态
            Map paramRm = new HashMap(2);
            paramRm.put("pid", pid);
            paramRm.put("menuId", menuId);
            paramRm.put("roleId", roleId);
            List<RoleMenu> broRms = roleMenuMapper.findByPidExcMenuId(paramRm);
            /*
            *   如果有兄弟节点，代表最起码有一个已选中，不需要变更父节点选中状态
            *   如果没有兄弟节点，代表全是未选中,直接更新父节点选中状态
            */
            if (broRms.size() == 0){
                if (checked){
                    menuIds4Insert.add(pid);
                }
                else {
                    menuIds4Delete.add(pid);
                }
            }
        }

        //批量新增
        if (menuIds4Insert.size() > 0){
            RoleMenu rm = new RoleMenu();
            rm.setCreator(getCurrentUser().getUserId());
            rm.setCtime(now);
            rm.setUpdateTime(now);
            rm.setRoleId(roleId);
            for (Integer mId : menuIds4Insert) {
                rm.setRmId(null);
                rm.setMenuId(mId);
                roleMenuService.insertSelective(rm);
            }
        }

        //批量删除
        if (menuIds4Delete.size() > 0) {
            RoleMenu rm = new RoleMenu();
            rm.setRoleId(roleId);
            for (Integer mId : menuIds4Delete) {
                rm.setRmId(null);
                rm.setMenuId(mId);
                roleMenuService.deleteSelective(rm);
            }
        }

        return new ResultBean(ResultBean.Code.success);
    }

    @RequestMapping("update")
    @ResponseBody
    @ArchivesLog(message = "修改角色权限")
    public ResultBean update(String menuArr, Integer roleId){
        //查询该role的所有菜单
        List<Integer> menuIds = new ArrayList<Integer>();
        List<Integer> roleMenuIds = new ArrayList<Integer>();
        RoleMenu paramRecord = new RoleMenu();
        paramRecord.setRoleId(roleId);
        List<RoleMenu> roleMenus = roleMenuService.selectAll(null, paramRecord);
        if (roleMenus.size() > 0){
            for (RoleMenu roleMenu : roleMenus) {
                if (!StringUtil.isNotEmpty(menuArr)){
                    roleMenuIds.add(roleMenu.getRmId());
                }else{
                    menuIds.add(roleMenu.getMenuId());
                }
            }
        }

        //如果是全部未勾选，直接删除
        if (!StringUtil.isNotEmpty(menuArr)){
            roleMenuService.deleteBatch(roleMenuIds.toArray(new Integer[roleMenuIds.size()]));
        }else{
            //提取menuArr
            String[] tmpMenuArr = menuArr.split(",");
            if (tmpMenuArr.length > 0){
                //遍历前台传过来的menuId
                for (int i = 0; i < tmpMenuArr.length; i++) {
                    String tmp = tmpMenuArr[i];
                    String[] strs = tmp.split("@");
                    //菜单id
                    int tmpMenuId = Integer.valueOf(strs[0]);
                    //是否选择
                    int tmpChecked = Integer.valueOf(strs[1]);
                    //判断tmpMenuId是否原先就有
                    if (menuIds.contains(tmpMenuId)){
                        //判断tmpMenuId是否仍被选中
                        if (tmpChecked == 0) {
                            continue;
                        }
                        //这回没有被选中，因此需要删除
                        else {
                            RoleMenu roleMenu = new RoleMenu();
                            roleMenu.setRoleId(roleId);
                            roleMenu.setMenuId(tmpMenuId);
                            roleMenuService.deleteSelective(roleMenu);
                        }
                    }
                    //原先没有但这回有，那么直接添加
                    else {
                        Date now = new Date();
                        RoleMenu roleMenu = new RoleMenu();
                        roleMenu.setMenuId(tmpMenuId);
                        roleMenu.setRoleId(roleId);
                        roleMenu.setUpdateTime(now);
                        roleMenu.setCtime(now);
                        roleMenu.setCreator(getCurrentUser().getUserId());
                        roleMenuService.insertSelective(roleMenu);
                    }
                }
            }
        }

        return new ResultBean(ResultBean.Code.success);
    }


}